use std::sync::Arc;

use model_graph_types::peer::{get_peer_id, is_self};

use crate::{
    data_channels::request::ping,
    signaling::{message::SignalMessageContent, request_response},
    transport::{exist_connection, prepare_follower, remove_connection},
};

use super::{FamilyMessage, RraiMessage};

pub async fn on_message(peer_id: &String, message: &RraiMessage) -> anyhow::Result<Option<String>> {
    //
    match message {
        RraiMessage::Family(msg) => _family(peer_id, msg).await,
        _ => {
            tracing::debug!("");
            Ok(None)
        }
    }
}

async fn _family(peer_id: &String, peers: &FamilyMessage) -> anyhow::Result<Option<String>> {
    //
    let self_peer = get_peer_id()?;

    //peer_id,dtype,is_online
    for peer in peers {
        if is_self(&peer.0)? {
            // tracing::debug!("节点不在线或者是自身!{}", &peer.peer_id);
            continue;
        }
        if peer.2 != 1 {
            // tracing::debug!("节点不在线或者是自身!{}", &peer.peer_id);
            // 不在线， 检查是否有连接，删除连接
            let _ = remove_connection(&peer.0);
            continue;
        }
        if exist_connection(&peer.0)? {
            tracing::debug!("连接存在!{}", &peer.0);
            let _ = ping(&peer.0).await;
            continue;
        }
        //如果自身的peer id > 对方的
        if self_peer > peer.0 {
            if let Err(err) = prepare_follower(&peer.0).await {
                tracing::error!("{}建立数据通道请求失败!{}", &peer.0, err);
            } else {
                tracing::error!("{}建立数据通道请求!", &peer.0);
            }
        }
    }
    Ok(None)
}

pub async fn request_family() -> anyhow::Result<()> {
    let response = request_response(
        &String::from("rrai"),
        serde_json::json!({
            "type":"family",
            "data":{}
        }),
        60000,
    )
    .await?;
    let src = response.src.clone();

    match response.data {
        Some(SignalMessageContent::Rrai { err, data }) => {
            if let Some(RraiMessage::Family(peers)) = data {
                let _ = _family(&src, &peers).await?;
            }
        }
        _ => {
            tracing::error!("request_family返回消息类型不对！");
        }
    }
    Ok(())
}
